/*
 * @Description:基于 axios 封装的 rn 项目的协议工具
 * @Author: jun.fu
 * @Date: 2019-02-19 16:19:50
 * @Last Modified by:   jun.fu
 * @Last Modified time: 2019-02-19 16:19:50
 */
import { ajax } from 'js-xiaobu-utils'
import axios from 'axios'
import { AsyncStorage } from 'react-native'
import sign from './sign.min.js'
import { showToast } from '../utils/ToastUtils'

/**
 * 封装的协议发送工具
 * 调用方式ajaxAsync(url,paramsObj).then(function(body){}).catch(function(error){});
 * @param {String} api 协议基础地址
 * @param {String} token 协议token
 * @param {String} urlString 协议地址
 * @param {Object} sendObj 参数
 * @param {3000|Number} timeout 协议超时时间
 * @param {Number} autoExLvl 自动处理异常等级,0表示都处理异常，1表示只自动处理协议网络异常，2表示不自动处理异常
 */
async function ajaxAsyncRN (
  api,
  token,
  urlString,
  sendObj,
  timeout = 3000,
  autoExLvl = 0
) {
  // 协议取消方法创建
  let cancelToken = axios.CancelToken
  let source = cancelToken.source()

  // 页面onpause时取消发送
  // TODO:暂时关闭，等待安卓修改地图页面的纠错无法接受到onresumebug
  // if (window.pause) {
  //   source.cancel(`取消发送${urlString}`)
  // }
  // 请求处理等级，布尔值转换
  if (autoExLvl === true) autoExLvl = 0
  else if (autoExLvl === false) autoExLvl = 2
  let url =
    (urlString.startsWith('/') ? urlString : urlString + '/') +
    '?token=' +
    token
  let sessionID = ''
  try {
    const sessionIDCopy = await AsyncStorage.getItem('XIAOBUSESSION')
    if (sessionIDCopy) {
      sessionID = sessionIDCopy
    }
  } catch (e) {
  }

  try {
    return await ajax(
      api,
      timeout,
      url,
      sign(JSON.stringify(sendObj), token, sessionID),
      sessionID,
      autoExLvl,
      source
    )
  } catch (error) {
    if (error.needLogin) {
      console.log('需要登录')
    }
    if (error.toastMsg) {
      console.log('需要toast')
      toastFunction(error.toastMsg, error.errCode)
    }
    // throw error.error
    throw error
  }
}

// // 登录函数
// function loginFunction() {
//   // toastFunction(toastMsg)
//   console.error('请登录')
// }

function toastFunction (toastMsg, errCode) {
  let toast = true
  // if (window.pause) {
  //     toast = false
  if (
    errCode === '401' ||
    errCode === '403' ||
    errCode === '400011' ||
    errCode === '400003'
  ) {
    toast = true
  }
  // }
  if (toast) {
    if (toastMsg && toastMsg !== '') {
      console.log('--------------协议toast--------------')
      console.log(toastMsg)
      // if (window.x_toast) {
      //   window.x_toast.showShortBottom(toastMsg, () => {}, () => {})
      // }
      // ToastAndroid.show(toastMsg, ToastAndroid.SHORT)
      showToast(toastMsg)
    }
  }
}

export default ajaxAsyncRN
